import React, { useEffect, useState, useRef } from "react";
import PropTypes from "prop-types";
import videojs from 'video.js';
import "videojs-contrib-hls";
import "video.js/dist/video-js.css";
import style from "./index.less";
// 给window上添加videojs, zh-CN.js 语言注册依赖 videojs.addLanguage()方法
// 配置了不生效的话  把public/index.html  里的标签  <html lang="en">  </html>   lang设置为 "zh-CN"
// window.videojs = Videojs;
// import("video.js/dist/lang/zh-CN.js")

const VideoPlayer = (props) => {
  const videoRef = React.useRef(null);
  const playerRef = React.useRef(null);
  const { options, onReady } = props;


  useEffect(() => {
    if (!playerRef.current) {
      // The Video.js player needs to be _inside_ the component el for React 18 Strict Mode. 
      const videoElement = document.createElement("video-js");

      videoElement.classList.add('vjs-big-play-centered');
      videoRef.current.appendChild(videoElement);

      const player = playerRef.current = videojs(videoElement, options, () => {
        onReady && onReady(player);
      });

      // You could update an existing player in the `else` block here
      // on prop change, for example:
    } else {
      const player = playerRef.current;
      player.autoplay(options.autoplay);
      player.src(options.sources);
    }
  }, [videoRef]) //options, 

  useEffect(() => {
    const player = playerRef.current;

    return () => {
      console.log(player, player?.isDisposed)
      if (player && !player?.isDisposed) {
        player?.dispose();
        playerRef.current = null;
      }
    };
  }, [playerRef])

  return (
    <div data-vjs-player>
      <div ref={videoRef} />
    </div>
  )
}
export default VideoPlayer;